package com.hsj.busmanager.service;

import com.hsj.busmanager.api.Bus;
import com.hsj.busmanager.api.Position;
import com.hsj.busmanager.mapper.BusMapper;
import com.hsj.busmanager.mapper.PositionMapper;
import com.hsj.busmanager.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;

@Service
public class PositionSerivce {

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private BusMapper busMapper;

    public Position getByBusId(Integer busId) {
        return  positionMapper.getByBusId(busId);
    }

    public List<Position> getPositionList() {
        return positionMapper.getPositionList();
    }

    /**
     * 1、修改车辆经纬度并保存上次经度
     * 2、计算两次经纬度之间的距离并更新车辆本月行驶距离
     * @param position
     */
    public void handle(Position position) {
            //获取随机生成的经纬度
        double lon = CommonUtil.getLon();
        double lat = CommonUtil.getLat();

        //1、修改车辆经纬度并保存上次经度
        if(position.getLastLat() == null || position.getLastLat().equals("0")){
            position.setLastLat(lat+"");
        }else{
            position.setLastLat(position.getLat());
        }
        if(position.getLastLon() == null || position.getLastLon().equals("0")){
            position.setLastLon(lon+"");
        }else{
            position.setLastLon(position.getLon());
        }

        position.setLon(lon+"");
        position.setLat(lat+"");
        positionMapper.updateByPrimaryKeySelective(position);

        //计算两次经纬度之间的距离并更新车辆本月行驶距离
        double distance = CommonUtil.getDistance(lat,lon,Double.valueOf(position.getLastLat()),Double.valueOf(position.getLastLon()));
        distance = distance/1000;
        DecimalFormat df = new DecimalFormat("#.00");
        distance = Double.valueOf(df.format(distance));
        busMapper.updateDistanceByBusId(position.getBusId(),distance);
    }

}
